/**
 * desc: app init and route
 * author: Joe
 * date: 7/5/2018
 */

/* provider config
----------------------------------------------------------------------------- */
appModule.config(
  [
    '$provide', '$compileProvider', '$sessionStorageProvider', '$localStorageProvider', '$resourceProvider', '$locationProvider', '$routeProvider', '$mdIconProvider', '$mdThemingProvider', '$mdDateLocaleProvider', '$httpProvider',
    'setting', '$cookiesProvider',
    function ($provide, $compileProvider, $sessionStorageProvider, $localStorageProvider, $resourceProvider, $locationProvider, $routeProvider, $mdIconProvider, $mdThemingProvider, $mdDateLocaleProvider, $httpProvider, setting, $cookiesProvider) {
      $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|tel|file|sms|data|javascript):/);
      $mdDateLocaleProvider.shortMonths = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
      // // $mdDateLocaleProvider.shortMonths = ['janv', 'févr', 'mars', ...];
      //
      $mdDateLocaleProvider.shortDays = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
      // route
      $locationProvider.hashPrefix('!');
      // // $mdDateLocaleProvider.days = ['dimanche', 'lundi', 'mardi', ...];
      $routeProvider
      // 登录
        .when('/login', {templateUrl: 'views/login/login.template.html', controller: 'LoginController'})
        // 待办管理
        .when('/standby-management', {templateUrl: 'views/association/standby-management/standby-management.template.html', controller: 'StandbyManagement'})
        .otherwise('/login');
      // decorator
      $provide.decorator('$log', [
        '$delegate',
        function ($delegate) {
          var originalServiceLog = $delegate.log;
          $delegate.log = function (msg) {
            msg = '======Angular application log======\n' + msg;
            originalServiceLog.apply($delegate, arguments);
          };
          return $delegate;
        }
      ]);
      $provide.decorator('dateFilter', [
        '$delegate',
        function ($delegate) {
          var originalFilter = $delegate;

          function patchDefault(date, format, timezone) {
            if (!format) {
              format = 'yyyy-MM-dd';
            }
            format = 'yyyy-MM-dd';
            return originalFilter(date, format, timezone);
          }

          return patchDefault;
        },
      ]);

      // icon
      $mdIconProvider
      .icon('menu', './assets/icon_menu.svg', 24)
      .icon('home', './assets/icon_home.svg', 24)
      .icon('logout', './assets/icon_logout.svg', 24);

      // theme
      $mdThemingProvider
      .theme('default')
      .primaryPalette('blue', {default: '600'});
      // ajax service
      // $httpProvider.defaults.headers.post = { 'Content-Type' : 'Accept: application/json, text/plain, *﻿/﻿* '};

      // ajax service
      $httpProvider.interceptors.push([
        '$q',
        function($q) {
          return {
            request: function(config) {
              config.timeout = setting.timeout;

              if (conf.baseUrl) {
                config.url = config.url.replace(/^\//, conf.baseUrl + '/');
              }
              return config;
            },
            requestError: function(rejection) {
              return $q.reject(rejection);
            },
            response: function(response) {
              // add global interceptors here
              if (response.status) {
                // deal with status
              }

              if (angular.isObject(response.data)) {
                // deal with data.code
                if (response.data.error_code === '211'){
                  sessionStorage.clear();
                  location.reload();
                }
              }

              return response;
            },
            responseError: function(rejection) {
              return $q.reject(rejection);
            }
          };
        }
      ]);
      $resourceProvider.defaults.stripTrailingSlashes = false;

      // cookie
      $cookiesProvider.defaults.expires = new Date(Date.now() + setting.cookieExpire * 60 * 1000);
      // storage
      $localStorageProvider.setKeyPrefix(setting.storagePrefix);
      $sessionStorageProvider.setKeyPrefix(setting.storagePrefix);
      $localStorageProvider.set('website-category', 'backend-system');
    },
  ]
);

/* bootstrap config
----------------------------------------------------------------------------- */
appModule.run(
  [
    'routeTemplateMonitor', '$rootScope', '$location', '$http', '$sessionStorage', 'api', 'setting',
    function (routeTemplateMonitor, $rootScope, $location, $http, $sessionStorage, api, setting) {
      routeTemplateMonitor.start();
      // login status
      $rootScope.fileUrl = api.getAttachmentById;
      $rootScope.isLogin = $sessionStorage.isLogin | false;
      $http.defaults.headers.post = {'Content-Type': 'application/x-www-form-urlencoded'};
      $http.defaults.withCredentials = true;
      $rootScope.$on('$viewContentLoaded', function () {
        $rootScope.username = $sessionStorage.username;
        // SMValidator initial must after DOM rendered
        new SMValidator(setting.smValidatorNode, {
          // add validate rule here
          short: true
        });
        // prevent user from operation without login
        if (!$rootScope.isLogin) {
          $location.url('/login');
          $location.replace();
        }
        if ($location.url() === '/login') {
          $rootScope.isLogin =false;
        }
        if ($sessionStorage.menuList === undefined) {
        } else {
          $rootScope.menuList = $sessionStorage.menuList;
        }
        // prevent user goto login page in login status
        if ($rootScope.isLogin) {
          // $location.url('/standby-management');
        }
      });
    },
  ]
);

/* layout controller
----------------------------------------------------------------------------- */
appModule.controller('LayoutController',
  [
    '$rootScope', '$scope', 'TestingPdf', '$mdSidenav', '$http', 'TransFerence', '$sce', '$log', '$location', 'PhoneService', '$sessionStorage',
    function ($rootScope, $scope, TestingPdf, $mdSidenav, $http, TransFerence, $sce, $log, $location, PhoneService, $sessionStorage) {
      if (!TestingPdf()){
        currencyLayer('对不起,您还没有安装PDF阅读器软件呢,为了方便预览PDF文档,请选择安装！',function() {
          window.location.href = 'http://ardownload.adobe.com/pub/adobe/reader/win/9.x/9.3/chs/AdbeRdr930_zh_CN.exe';
        });
      }
      $scope.toggleMenu = function () {
        $mdSidenav('left').toggle();
      };
      $scope.logout = function () {
        $log.log('logout');
        $rootScope.isLogin = false;
        //退出请求消空
        $http({
          method: 'post',
          url: apis.logout
        }).then(function (data) {
        });
        $location.url('/login');
        $sessionStorage.isLogin = false;
      };
      var ModifyLay;
      $scope.goSetting = function () {
        $scope.user = {};
        ModifyLay = layer.open({
          type: 1,
          title: '修改密码',
          closeBtn: 1,
          area: ['650px', '400px'],
          shadeClose: true,
          skin: 'yourclass',
          content: $('.add-jue-box')
        });
      };
      // 确认修改密码
      $scope.updatePassVal = {
        password: '',
        newpassword: ''
      };
      $scope.repassword = '';
      $scope.confirmModify = function () {
        if ($scope.updatePassVal.oldpassword !== '' && $scope.updatePassVal.newpassword !== '' && $scope.repassword !== '') {
          if ($scope.updatePassVal.newpassword.length < 6 || $scope.updatePassVal.newpassword.length > 12){
            layer.msg('密码格式为6-12位字母或者数字');
            return;
          } else {
            if ($scope.updatePassVal.newpassword !== $scope.repassword) {
              layer.msg('两次输入的密码不一致');
            }else{
              PhoneService.rePassword.query(TransFerence($scope.updatePassVal)).$promise.then(function(res) {
                if (res.error_code === 0){
                  layer.msg('修改成功,请重新登录');
                  setTimeout(function() {
                    sessionStorage.clear();
                    location.reload();
                  },1000);
                } else{
                  layer.msg(res.error_msg);
                }
              });
            }
          }
        }else{
          layer.msg('请填写完整!');
        }
      };

      $scope.cancel = function(){
        layer.close(ModifyLay);
      };
      $scope.copyright = $sce.trustAsHtml('Powered by CMDA &copy; 2014–2018.');
      // $http.get('./menu.json').then(function(res) {
      //   $scope.menuList = res.data;
      // });
      // $scope.watch('menuList')
      $rootScope.tableSize = {};
      $http.get('./table.json').then(function (res) {
        $rootScope.tableSize = res.data;
      });
    }
  ]
);
